#include "ordermanagementui.h"
#include "errorhandler.h"
#include <QMessageBox>
#include <QApplication>
#include <QDialog>
#include <QGroupBox>
#include <QFormLayout>
#include <QTableWidget>
#include <QLabel>
#include <QPushButton>
#include <QHeaderView>

OrderManagementUI::OrderManagementUI(QWidget *parent)
    : QWidget(parent)
    , m_orderListWidget(nullptr)
    , m_orderControlWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_topLayout(nullptr)
    , m_orderManager(nullptr)
    , m_selectedOrderId("")
    , m_refreshTimer(nullptr)
    , m_isInitialized(false)
{
    // 获取OrderManager实例
    m_orderManager = &OrderManager::instance();
    
    // 创建定时器
    m_refreshTimer = new QTimer(this);
    m_refreshTimer->setInterval(30000); // 30秒自动刷新
    
    // 初始化界面
    initializeUI();
}

OrderManagementUI::~OrderManagementUI()
{
    // Qt会自动清理子对象，这里只需要处理特殊资源
}

void OrderManagementUI::initializeUI()
{
    if (m_isInitialized) {
        return;
    }
    
    try {
        // 创建子组件
        m_orderListWidget = new OrderListWidget(this);
        m_orderControlWidget = new OrderControlWidget(this);
        
        // 设置布局
        setupLayout();
        
        // 设置信号槽连接
        setupConnections();
        
        // 设置样式
        setupStyleSheet();
        
        // 加载初始数据
        loadOrders();
        
        m_isInitialized = true;
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::ERROR, "订单管理界面初始化失败", 
                     QString::fromStdString(e.what()), false);
    }
}

void OrderManagementUI::refreshData()
{
    if (!m_isInitialized) {
        return;
    }
    
    loadOrders();
}



// 订单管理器信号响应槽函数
void OrderManagementUI::onOrderCreated(const Order& order)
{
    if (m_orderListWidget) {
        m_orderListWidget->addOrder(order);
    }
}

void OrderManagementUI::onOrderStatusUpdated(const QString& orderId, 
                                            OrderStatus oldStatus, OrderStatus /*newStatus*/)
{
    Q_UNUSED(oldStatus)
    
    // 更新列表显示
    if (m_orderListWidget) {
        Order updatedOrder = m_orderManager->getOrderById(orderId);
        if (updatedOrder.isValid()) {
            m_orderListWidget->updateOrder(updatedOrder);
        }
    }
    
    // 如果是当前选中的订单，更新详情显示和控制按钮
    if (orderId == m_selectedOrderId) {
        Order updatedOrder = m_orderManager->getOrderById(orderId);
        if (updatedOrder.isValid()) {
            // 更新订单详情显示
            // 更新控制按钮状态
            if (m_orderControlWidget) {
                m_orderControlWidget->setCurrentOrder(updatedOrder);
            }
        }
    }
}

void OrderManagementUI::onOrderCompleted(const QString& orderId)
{
    showOperationResult(QString("订单 %1 已完成").arg(orderId));
}

void OrderManagementUI::onOrderCancelled(const QString& orderId, const QString& reason)
{
    Q_UNUSED(reason)
    showOperationResult(QString("订单 %1 已取消").arg(orderId));
}

// 子组件信号响应槽函数
void OrderManagementUI::onOrderSelected(const QString& orderId)
{
    m_selectedOrderId = orderId;
    
    // 获取订单详情并更新控制组件
    Order order = m_orderManager->getOrderById(orderId);
    if (order.isValid()) {
        if (m_orderControlWidget) {
            m_orderControlWidget->setCurrentOrder(order);
        }
    }
}

void OrderManagementUI::onOrderDoubleClicked(const QString& orderId)
{
    // 获取订单详情并显示弹窗
    Order order = m_orderManager->getOrderById(orderId);
    if (order.isValid()) {
        showOrderDetailDialog(order);
    } else {
        QMessageBox::warning(this, "提示", "未找到该订单信息");
    }
}

void OrderManagementUI::onSearchCriteriaChanged(const OrderSearchCriteria& criteria)
{
    m_currentCriteria = criteria;
    
    try {
        // 根据搜索条件获取订单
        QList<Order> filteredOrders;
        if (criteria.hasFilters()) {
            filteredOrders = m_orderManager->searchOrders(criteria);
        } else {
            filteredOrders = m_orderManager->getAllOrders();
        }
        
        m_currentOrders = filteredOrders;
        
        if (m_orderListWidget) {
            m_orderListWidget->setOrders(filteredOrders);
        }
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::WARNING, "搜索订单失败", 
                     QString::fromStdString(e.what()), false);
    }
}

void OrderManagementUI::onStatusChangeRequested(const QString& orderId, OrderStatus newStatus)
{
    try {
        OrderOperationResult result = m_orderManager->updateOrderStatus(orderId, newStatus);
        
        if (result == OrderOperationResult::SUCCESS) {
            QString statusText = OrderManager::getStatusDisplayText(newStatus);
            showOperationResult(QString("订单状态已更新为: %1").arg(statusText));
        } else {
            QString errorMsg = OrderManager::getOperationResultMessage(result);
            showOperationResult(QString("状态更新失败: %1").arg(errorMsg), false);
        }
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::ERROR, "更新订单状态失败", 
                     QString::fromStdString(e.what()), false);
        showOperationResult("状态更新失败，请重试", false);
    }
}

void OrderManagementUI::onDeleteOrderRequested(const QString& orderId)
{
    try {
        OrderOperationResult result = m_orderManager->deleteOrder(orderId);
        
        if (result == OrderOperationResult::SUCCESS) {
            showOperationResult("订单已成功删除");
            
            // 如果删除的是当前选中的订单，清空选择
            if (orderId == m_selectedOrderId) {
                m_selectedOrderId.clear();
                if (m_orderControlWidget) {
                    m_orderControlWidget->clearCurrentOrder();
                }
            }
            
            // 刷新界面
            refreshData();
        } else {
            QString errorMsg = OrderManager::getOperationResultMessage(result);
            showOperationResult(QString("删除订单失败: %1").arg(errorMsg), false);
        }
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::ERROR, "删除订单失败", 
                     QString::fromStdString(e.what()), false);
        showOperationResult("删除订单失败，请重试", false);
    }
}

void OrderManagementUI::onRefreshRequested()
{
    refreshData();
    showOperationResult("数据已刷新");
}

void OrderManagementUI::setupLayout()
{
    // 创建主布局 - 单列布局，不再使用分割器
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(8, 8, 8, 8);
    m_mainLayout->setSpacing(6);
    
    // 顶部控制区域
    m_topLayout = new QHBoxLayout();
    m_topLayout->addWidget(m_orderControlWidget);
    
    // 添加到主布局
    m_mainLayout->addLayout(m_topLayout);
    m_mainLayout->addWidget(m_orderListWidget);
    
    // 设置布局比例
    m_mainLayout->setStretchFactor(m_topLayout, 0);         // 固定高度
    m_mainLayout->setStretchFactor(m_orderListWidget, 1);   // 主要内容
}

void OrderManagementUI::setupConnections()
{
    // 连接OrderManager信号
    connect(m_orderManager, &OrderManager::orderCreated,
            this, &OrderManagementUI::onOrderCreated);
    connect(m_orderManager, &OrderManager::orderStatusUpdated,
            this, &OrderManagementUI::onOrderStatusUpdated);
    connect(m_orderManager, &OrderManager::orderCompleted,
            this, &OrderManagementUI::onOrderCompleted);
    connect(m_orderManager, &OrderManager::orderCancelled,
            this, &OrderManagementUI::onOrderCancelled);
    
    // 连接子组件信号
    if (m_orderListWidget) {
        connect(m_orderListWidget, &OrderListWidget::orderSelected,
                this, &OrderManagementUI::onOrderSelected);
        connect(m_orderListWidget, &OrderListWidget::orderDoubleClicked,
                this, &OrderManagementUI::onOrderDoubleClicked);
    }
    
    if (m_orderControlWidget) {
        connect(m_orderControlWidget, &OrderControlWidget::searchCriteriaChanged,
                this, &OrderManagementUI::onSearchCriteriaChanged);
        connect(m_orderControlWidget, &OrderControlWidget::statusChangeRequested,
                this, &OrderManagementUI::onStatusChangeRequested);
        connect(m_orderControlWidget, &OrderControlWidget::deleteOrderRequested,
                this, &OrderManagementUI::onDeleteOrderRequested);
        connect(m_orderControlWidget, &OrderControlWidget::refreshRequested,
                this, &OrderManagementUI::onRefreshRequested);
    }
    
    // 连接定时器
    connect(m_refreshTimer, &QTimer::timeout,
            this, &OrderManagementUI::refreshData);
    
    // 延迟连接DataManager的外部文件变更信号，避免初始化冲突
    QTimer::singleShot(100, this, [this]() {
        connect(&DataManager::instance(), &DataManager::externalFileChanged,
                this, &OrderManagementUI::onExternalFileChanged);
    });
    
    // 连接OrderManager的订单变更信号
    connect(m_orderManager, &OrderManager::ordersChanged,
            this, &OrderManagementUI::refreshData);
    
    // 启动定时器
    m_refreshTimer->start();
}

void OrderManagementUI::setupStyleSheet()
{
    // 设置主界面样式，与现有管理员界面保持一致
    setStyleSheet(R"(
        OrderManagementUI {
            background-color: #FAFAFA;
            font-family: 'Microsoft YaHei', sans-serif;
            font-size: 11px;
        }
        
        QSplitter::handle {
            background-color: #E0E0E0;
            width: 3px;
        }
        
        QSplitter::handle:hover {
            background-color: #BDBDBD;
        }
    )");
}

void OrderManagementUI::loadOrders()
{
    try {
        QList<Order> orders;
        
        if (m_currentCriteria.hasFilters()) {
            orders = m_orderManager->searchOrders(m_currentCriteria);
        } else {
            orders = m_orderManager->getAllOrders();
        }
        
        m_currentOrders = orders;
        
        if (m_orderListWidget) {
            m_orderListWidget->setOrders(orders);
        }
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::ERROR, "加载订单数据失败", 
                     QString::fromStdString(e.what()), false);
    }
}

void OrderManagementUI::showOperationResult(const QString& /*message*/, bool /*success*/)
{
    // 这里可以添加状态栏显示或其他用户反馈机制
}

void OrderManagementUI::onExternalFileChanged(DataType dataType, const QString& /*filePath*/)
{
    // 当检测到外部文件变更时，刷新相关数据
    if (dataType == DataType::ORDERS) {
        // 延迟刷新，确保文件写入完成
        QTimer::singleShot(100, this, [this]() {
            refreshData();
        });
    } else if (dataType == DataType::MENU) {
        // 菜单数据变更也可能影响订单显示（如菜品名称变更）
        QTimer::singleShot(100, this, [this]() {
            refreshData();
        });
    }
}

void OrderManagementUI::showOrderDetailDialog(const Order& order)
{
    // 创建订单详情对话框
    QDialog* dialog = new QDialog(this);
    dialog->setWindowTitle(QString("订单详情 - %1").arg(order.id));
    dialog->setModal(true);
    dialog->resize(600, 500);
    
    QVBoxLayout* layout = new QVBoxLayout(dialog);
    layout->setContentsMargins(15, 15, 15, 15);
    layout->setSpacing(15);
    
    // 基本信息
    QGroupBox* basicGroup = new QGroupBox("订单基本信息");
    QFormLayout* basicLayout = new QFormLayout(basicGroup);
    basicLayout->addRow("订单号:", new QLabel(order.id));
    basicLayout->addRow("顾客ID:", new QLabel(order.customerId));
    QString statusText;
    switch (order.status) {
        case OrderStatus::PENDING: statusText = "待处理"; break;
        case OrderStatus::PREPARING: statusText = "制作中"; break;
        case OrderStatus::COMPLETED: statusText = "已完成"; break;
        case OrderStatus::CANCELLED: statusText = "已取消"; break;
        default: statusText = "未知"; break;
    }
    basicLayout->addRow("状态:", new QLabel(statusText));
    basicLayout->addRow("下单时间:", new QLabel(order.createdDate.toString("yyyy-MM-dd hh:mm:ss")));
    basicLayout->addRow("总金额:", new QLabel(QString("¥%1").arg(order.totalAmount, 0, 'f', 2)));
    basicLayout->addRow("支付方式:", new QLabel(order.paymentMethod.isEmpty() ? "未指定" : order.paymentMethod));
    
    // 订单明细
    QGroupBox* itemsGroup = new QGroupBox("订单明细");
    QVBoxLayout* itemsLayout = new QVBoxLayout(itemsGroup);
    
    QTableWidget* itemsTable = new QTableWidget();
    itemsTable->setColumnCount(4);
    itemsTable->setHorizontalHeaderLabels({"菜品名称", "数量", "单价", "小计"});
    itemsTable->setRowCount(order.items.size());
    itemsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    itemsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    itemsTable->setAlternatingRowColors(true);
    
    for (int i = 0; i < order.items.size(); ++i) {
        const OrderItem& item = order.items[i];
        itemsTable->setItem(i, 0, new QTableWidgetItem(item.menuItemName));
        itemsTable->setItem(i, 1, new QTableWidgetItem(QString::number(item.quantity)));
        itemsTable->setItem(i, 2, new QTableWidgetItem(QString("¥%1").arg(item.price, 0, 'f', 2)));
        itemsTable->setItem(i, 3, new QTableWidgetItem(QString("¥%1").arg(item.quantity * item.price, 0, 'f', 2)));
    }
    
    itemsTable->resizeColumnsToContents();
    itemsLayout->addWidget(itemsTable);
    
    // 关闭按钮
    QPushButton* closeButton = new QPushButton("关闭");
    connect(closeButton, &QPushButton::clicked, dialog, &QDialog::accept);
    
    layout->addWidget(basicGroup);
    layout->addWidget(itemsGroup);
    layout->addWidget(closeButton);
    
    dialog->exec();
    dialog->deleteLater();
}
